//
//  LMMainViewController.swift
//  WeiBo
//
//  Created by Li MAc on 2018/11/13.
//  Copyright © 2018 Li MAc. All rights reserved.
//

import UIKit
import YYModel
class LMMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        
        //添加按钮
        setupbut()
        
        //添加新特新欢迎界面
        setupNewView()
        
//        self.tabBarController?.delegate = self as? UITabBarControllerDelegate
        //设置TabBarController代理
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(tongzhiFunc), name: NSNotification.Name(rawValue: TongZhi), object: nil)
        
    }
    
    deinit {
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    
    private lazy var but : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

    
    @objc private func butAction(){
        print("点击了按钮")
    }
    
    
    @objc func tongzhiFunc(n:Notification){
        print("66666\(n))")
        let vc = LMOAuthViewController()
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil )
    }
    
}


extension LMMainViewController {
    
    //设置按钮
    private func setupbut(){
        //计算按钮的宽度 children是控制页面的个数
        let count = CGFloat(children.count)
        //减 1 的目的是按钮之间具有容错点
//        let w = (tabBar.bounds.width / count) - 1
          let w = (tabBar.bounds.width / count)
        //按钮的位置  insetBy（缩进）
        but.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        but.addTarget(self, action: #selector(butAction), for: .touchUpInside)
        tabBar.addSubview(but)
    }
    
    
    private func setupChildControllers(){
        
       guard let path = Bundle.main.path(forResource: "demm.josn", ofType: nil),
        let da = NSData(contentsOfFile: path),
        let array = try? JSONSerialization.jsonObject(with: da as Data, options: []) as? [[String:AnyObject]]
        else{
            return
        }
        
        
//        let array  = [
//            ["clsName":"LMHomeViewController" ,
//             "title":"微博" ,
//             "imageName":"home",
//             "visitorDict":["imgName":"","message":"关注一些人，回这里看看有什么惊喜"]],
//
//            ["clsName":"LMMessageViewController",
//          "title":"消息",
//      "imageName":"message_center",
//      "visitorDict":["imgName":"visitordiscover_image_message","message":"登陆后，别人评论了你，发给你消息，都会在这里收到通知"]
//    ],
//
//            ["clsName":""],
//
//            ["clsName":"LMDiscoverViewController",
//          "title":"发现",
//      "imageName":"discover",
//      "visitorDict":["imgName":"visitordiscover_image_message","message":"登陆后，最新，最热微博尽在c掌握，不再与实事潮流擦肩w而过"]],
//
//            ["clsName":"LMProfileViewController",
//          "title":"我",
//      "imageName":"profile",
//      "visitorDict":["imgName":"visitordiscover_image_profile","message":"登陆后，你的微博，相册，个人资料都会显示在这里，显示给别人"]]
//        ]
//
//        //将数组array转换成josn
//
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//
//        (data as NSData).write(toFile: "/Users/numb/Desktop/WeiBo/demm.josn", atomically: true)
        
        
        var arrayM = [UIViewController]()
        
        for dictt in array!{
            
            arrayM.append(controller(dict: dictt as [String : AnyObject]))
        }
        viewControllers = arrayM
    }
    //使用字典创建一个字控制器
    
    //dict:信息字典[clsName,title（下标题）,imageName（图片）]
    
    private func controller(dict:[String:AnyObject])-> UIViewController {
        
        //1.取得字典内容
        
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName =  dict["imageName"] as? String,
            
            // Bundle.main.infoDictionary?[CFBundleName](动态获取命名空间的名称)
            //设置跟控制器需要添加命名空间 ->
            
            //Bundle.main.infoDictionary info获取
        let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? LMBaseViewController.Type,
            let dicc = dict["visitorDict"] as?[String:String]
        else  {
            return UIViewController()
        }
        
        //2.创建视图控制器
        let vc = cls.init()
        //设置控制器的访客信息字典
        vc.dicttt = dicc
        
        vc.title = title
        //设置tabar的图片
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        //设置其渲染图片
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        
        //设置tabbar的标题颜色（以下是swift的变化）
        
//      vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted);
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.orange], for: .highlighted);
        
        //设置tabbar的标题字体大小（以下是swift的变化）
        
//vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: .normal);
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)], for: .normal);
        
        let nav = LMNavigtionController(rootViewController:vc)
        
   return nav
    }
}

//是否切换到目标l控制器
extension LMMainViewController:UITabBarControllerDelegate{
    
     func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool{
        
        
       let dd = (children as NSArray).index(of: viewController)
        //判断是否是首页，同时 dd也是首页 重复点击首页则刷新
        if selectedIndex == 0 && dd == selectedIndex{
            print("点击了首页")
            let nav = children[0] as! UINavigationController
            let vc = nav.children[0] as! LMHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            DispatchQueue.main.asyncAfter(wallDeadline: DispatchWallTime.now() + 1) {
                 vc.loadDataa()
            }
        }
        
        
        //isMember 是那个类，但不包括子类
//        viewController.isMember(of: UIViewController.self)
        
        return !viewController.isMember(of: UIViewController.self)
    }
}

// Mark ：新特性界面
extension LMMainViewController {

    private func setupNewView(){
        
        if !LMNetworkTools.shared.userLogno{
            return
        }

        //判断是否是最新版本
        let v = isNewReissue ? LMNewFeatures.newFeatures() : LMWelcome.comView()

        v.frame = view.bounds

        view.addSubview(v)
    }

    
    private var isNewReissue : Bool {

        //从中输出结果中搜索当前版本，截取其对应的key
        print(Bundle.main.infoDictionary)
        //获取当前的版本info.plist可以看到
        var ban = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""

        //创建 vesion 保存在沙盒
        let path : String = ("vesion" as NSString).cz_appendDocumentDir()
        //取沙盒中的版本 取需要加 try? 当前里面是没有数据
        let shahe = try? String(contentsOfFile: path) ?? ""
        //将当前的版本写入在沙盒中
        _ = try?  ban.write(toFile:path ,atomically:true, encoding:.utf8)
    
        return ban != shahe
    }
}
